﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Web;
using System.Net;
using System.IO.Compression;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;

namespace BaccaratRally.BBinKiller
{
    public partial class FormMain : Form
    {
        public List<Bet> BetList;
        public List<Road> RoadList;

        Bitmap hostPic1 = null;
        Bitmap guestPic1 = null;
        Bitmap equalPic1 = null;

        Bitmap hostPic2 = null;
        Bitmap guestPic2 = null;
        Bitmap equalPic2 = null;

        Bitmap hostPic3 = null;
        Bitmap guestPic3 = null;
        Bitmap equalPic3 = null;

        public int blockWidth = 27;
        public int blockHeight = 35;

        public Boolean ShowGame;
        public DateTime LastSubmitTime;

        public DateTime LastSetTime1;
        public DateTime LastSetTime2;
        public DateTime LastSetTime3;

        public Boolean TableStatus1;
        public Boolean TableStatus2;
        public Boolean TableStatus3;

        public string RoundID1;
        public string RoundID2;
        public string RoundID3;

        public FormMain()
        {
            InitializeComponent();
            FillSiteList();

            BetList = new List<Bet>() { };
            RoadList = new List<Road>() { };

            ShowGame = true;

            this.txbOffset.Text = ConfigurationManager.AppSettings["ScreenOffset"];

            LastSetTime1 = DateTime.Now.AddMinutes(-1);
            LastSetTime2 = DateTime.Now.AddMinutes(-1);
            LastSetTime3 = DateTime.Now.AddMinutes(-1);

            this.wbMain.AllowWebBrowserDrop = false;
            ((SHDocVw.DWebBrowserEvents_Event)wbMain.ActiveXInstance).NewWindow += wbMain_NewWindow;
        }

        private void timerMain_Tick(object sender, EventArgs e)
        {
            timerMain.Stop();
            this.TopMost = true;

            #region GetTable Status
            TableStatus1 = CanSetBet(1);
            TableStatus2 = CanSetBet(2);
            TableStatus3 = CanSetBet(3);
            #endregion

            #region GetReuslt
            #region table 1
            if (TableStatus1)
            {
                if (LastSetTime1.AddSeconds(30) < DateTime.Now)
                {
                    string nextroad = GetNextRoad(1, RoundID1);
                    if (nextroad != "")
                    {
                        Bet b = new Bet() { TableNo = 1, BetTime = DateTime.Now, BetSize = GetBetSize(), BetStatus = 0, Direction = nextroad, RoundID = RoundID1 };
                        LastSetTime1 = DateTime.Now;
                        BetList.Add(b);
                    }
                }
            }
            else
            {
                Byte gameResult1 = GetLastGameResult1();
                if (gameResult1 > 0 && gameResult1 < 10)
                {
                    SetReustl(1, ConvertResult(gameResult1), RoundID1);
                }
            }
            #endregion

            #region table 2
            if (TableStatus2)
            {
                if (LastSetTime2.AddSeconds(30) < DateTime.Now)
                {
                    string nextroad = GetNextRoad(2, RoundID2);
                    if (nextroad != "")
                    {
                        Bet b = new Bet() { TableNo = 2, BetTime = DateTime.Now, BetSize = GetBetSize(), BetStatus = 0, Direction = nextroad, RoundID = RoundID2 };
                        LastSetTime2 = DateTime.Now;
                        BetList.Add(b);
                    }
                }
            }
            else
            {
                Byte gameResult2 = GetLastGameResult2();
                if (gameResult2 > 0 && gameResult2 < 10)
                {
                    SetReustl(2, ConvertResult(gameResult2), RoundID2);
                }
            }
            #endregion

            #region table 3
            if (TableStatus3)
            {
                if (LastSetTime3.AddSeconds(30) < DateTime.Now)
                {
                    string nextroad = GetNextRoad(3, RoundID3);
                    if (nextroad != "")
                    {
                        Bet b = new Bet() { TableNo = 3, BetTime = DateTime.Now, BetSize = GetBetSize(), BetStatus = 0, Direction = nextroad, RoundID = RoundID3 };
                        LastSetTime3 = DateTime.Now;
                        BetList.Add(b);
                    }
                }
            }
            else
            {
                Byte gameResult3 = GetLastGameResult3();
                if (gameResult3 > 0 && gameResult3 < 10)
                {
                    SetReustl(3, ConvertResult(gameResult3), RoundID3);
                }
            }
            #endregion
            #endregion

            if (LastSubmitTime.AddSeconds(5) < DateTime.Now)
            {
                Bet b = (from bl in BetList where bl.BetStatus == 0 orderby bl.BetTime ascending select bl).FirstOrDefault();
                if (b != null)
                {
                    ClickBet(b.TableNo, b.Direction, b.BetSize);
                    (from bl in BetList where bl.BetStatus == 0 orderby bl.BetTime ascending select bl).FirstOrDefault().BetStatus = 2;
                }
            }

            Calc();
            timerMain.Start();
        }

        private void btnStartGame_Click(object sender, EventArgs e)
        {
            if (btnStartGame.Text == "开始")
            {
                HtmlElementCollection eles = wbMain.Document.Window.Frames[0].Document.GetElementsByTagName("object");

                foreach (HtmlElement ele in eles)
                {
                    if (ele.InnerHtml.Contains("MultiBetEmbed.swf"))
                    {
                        ele.Parent.Parent.Id = "";
                        ele.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px; width:860px; height: 600px; visibility: visible;";
                    }
                }

                btnStartGame.Text = "暂停";
                OnStart();
                timerMain.Enabled = true;
                timerMain.Start();

            }
            else
            {
                timerMain.Stop();
                btnStartGame.Text = "开始";
                SaveRoad(RoundID1);
                SaveRoad(RoundID2);
                SaveRoad(RoundID3);
                this.TopMost = false;
            }
        }

        public string GetLastRoad(Byte tableno, string roundid)
        {
            string LastRoad = "";

            List<Road> rList = (from rl in RoadList where rl.TableNO == tableno && rl.Result != "D" && rl.RoundID == roundid orderby rl.GameTime descending select rl).ToList();

            for (int i = 0; i < 16; i++)
            {
                if (rList.Count > i)
                {
                    LastRoad = LastRoad + rList[i].Result;
                }
            }

            return LastRoad;
        }

        public string GetNextRoad(Byte tableno, string roundid)
        {
            string lastRoad = GetLastRoad(tableno, roundid);
            string nextRoad = "";

            if (ConfigurationManager.AppSettings["InRoad"] == "1")
            {
                if (lastRoad.StartsWith("BB") || lastRoad.StartsWith("PP")) nextRoad = lastRoad.Substring(0, 1);
                if (lastRoad.StartsWith("BP") || lastRoad.StartsWith("PB")) nextRoad = lastRoad.Substring(1, 1);
                if (lastRoad.StartsWith("BBPPB") || lastRoad.StartsWith("PPBBP")) nextRoad = lastRoad.Substring(2, 1);
                if (lastRoad.StartsWith("PBBPPB") || lastRoad.StartsWith("BPPBBP")) nextRoad = lastRoad.Substring(0, 1);
            }
            else if (ConfigurationManager.AppSettings["InRoad"] == "2")
            {
                if (lastRoad.StartsWith("BB") || lastRoad.StartsWith("PP")) nextRoad = lastRoad.Substring(0, 1);
                if (lastRoad.StartsWith("BP") || lastRoad.StartsWith("PB")) nextRoad = lastRoad.Substring(1, 1);
                if (lastRoad.StartsWith("BBPPB") || lastRoad.StartsWith("PPBBP")) nextRoad = lastRoad.Substring(2, 1);
                if (lastRoad.StartsWith("PBBPPB") || lastRoad.StartsWith("BPPBBP")) nextRoad = lastRoad.Substring(0, 1);

                if (lastRoad.Length > 15)
                {
                    decimal rr = 0M;

                    for (int i = 0; i < 10; i++)
                    {
                        rr += GetRoundInResult(lastRoad.Substring(i, 1), lastRoad.Substring(i + 1, 6));
                    }

                    if (rr < 0)
                    { 
                        nextRoad = (nextRoad == "P") ? "B" : "P";
                    }
                }
            }
            else
            {
                Random rbd = new Random(Guid.NewGuid().GetHashCode());
                double rbdr = rbd.NextDouble();
                nextRoad = (rbdr > 0.5) ? "B" : "P";
            }

            return nextRoad;
        }

        private Decimal GetBetSize()
        {
            Decimal BetSize = Decimal.Parse(ConfigurationManager.AppSettings["BaseSize"]);
            Random rbd = new Random(Guid.NewGuid().GetHashCode());
            double rbdr = rbd.NextDouble();

            Decimal DynamicSize = Decimal.Parse(ConfigurationManager.AppSettings["DynamicSize"]);

            if (DynamicSize > 0M) 
            {
                if (rbdr > 0.8) BetSize += DynamicSize;
                if (rbdr > 0.97) BetSize += DynamicSize;
            }

            return BetSize;

        }

        private Decimal GetRoundInResult(string b, string r)
        {
            Decimal resulst = 0M;

            if (r.StartsWith("BB") || r.StartsWith("PP"))
            {
                resulst = (r.Substring(0, 1) == b) ? 1M : -1M;
            }
            if (r.StartsWith("BP") || r.StartsWith("PB"))
            {
                resulst = (r.Substring(1, 1) == b) ? 1M : -1M;
            }
            if (r.StartsWith("BBPPB") || r.StartsWith("PPBBP"))
            {
                resulst = (r.Substring(2, 1) == b) ? 1M : -1M;
            }
            if (r.StartsWith("PBBPPB") || r.StartsWith("BPPBBP"))
            {
                resulst = (r.Substring(0, 1) == b) ? 1M : -1M;
            }

            return resulst;
        }

        public void SetReustl(Byte tableno, string result, string roundid)
        {
            RoadList.Add(new Road() { GameTime = DateTime.Now, Result = result, TableNO = tableno, RoundID = roundid });

            Bet b = (from bl in BetList where bl.TableNo == tableno orderby bl.BetTime descending select bl).FirstOrDefault();
            if (b != null)
            {
                if (b.BetStatus < 6)
                {
                    (from bl in BetList where bl.TableNo == tableno orderby bl.BetTime descending select bl).FirstOrDefault().BetResult = result;
                    (from bl in BetList where bl.TableNo == tableno orderby bl.BetTime descending select bl).FirstOrDefault().BetStatus = 6;

                    if (result == "D")
                    {
                        (from bl in BetList where bl.TableNo == tableno orderby bl.BetTime descending select bl).FirstOrDefault().BetProfit = 0M;
                    }
                    else
                    {
                        if (b.Direction == result)
                        {
                            (from bl in BetList where bl.TableNo == tableno orderby bl.BetTime descending select bl).FirstOrDefault().BetProfit = (b.Direction == "B") ? 0.95M * b.BetSize : b.BetSize;
                        }
                        else
                        {
                            (from bl in BetList where bl.TableNo == tableno orderby bl.BetTime descending select bl).FirstOrDefault().BetProfit = 0 - b.BetSize;
                        }
                    }

                }
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if (this.cbbSiteList.SelectedItem == null)
            {
                return;
            }

            if (this.cbbSiteList.SelectedItem.ToString().Contains("$"))
            {
                this.wbMain.Navigate(this.cbbSiteList.SelectedItem.ToString().Split(new char[] { '$' })[1].Trim());
            }
            else
            {
                return;
            }

        }

        public void FillSiteList()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["ServiceUrl"] + "SiteList.aspx");

            #region Build HttpRequest
            request.Method = "GET";
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
            request.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            #endregion

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            String resultstring = "";

            if (response.ContentEncoding == "gzip")
            {
                Stream outStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress, true);
                StreamReader reader = new StreamReader(outStream, Encoding.GetEncoding("UTF-8"));
                resultstring = reader.ReadToEnd();
                reader.Close();
                outStream.Close();
            }
            else
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
                resultstring = reader.ReadToEnd();
                reader.Close();
            }

            if (resultstring.Contains("$"))
            {
                string[] sl = resultstring.Split(new char[] { '|' });
                for (int i = 0; i < sl.Length; i++)
                {
                    this.cbbSiteList.Items.Add(sl[i]);
                }
            }
        }

        private void OnStart()
        {
            LastSetTime1 = DateTime.Now.AddMinutes(-1);
            LastSetTime2 = DateTime.Now.AddMinutes(-1);
            LastSetTime3 = DateTime.Now.AddMinutes(-1);
            LastSubmitTime = DateTime.Now.AddMinutes(-1);

            BetList.Clear();

            this.lbTableSizeTotal.Text = "0";
            this.lbTableWinTotal.Text = "0";

            this.lbTableSize1.Text = "0";
            this.lbTableWin1.Text = "0";

            this.lbTableSize2.Text = "0";
            this.lbTableWin2.Text = "0";

            this.lbTableSize3.Text = "0";
            this.lbTableWin3.Text = "0";

            GetLastGameResult1();
            GetLastGameResult2();
            GetLastGameResult3();
        }

        private bool CanSetBet(int tableno)
        {
            bool result;
            int x = 180;
            int y = 449;

            x = x + int.Parse(this.txbOffset.Text) + (tableno - 1) * 286;


            Bitmap i;
            Graphics g;

            i = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            g = Graphics.FromImage(i);
            g.CopyFromScreen(new Point(this.Location.X, this.Location.Y), new Point(0, 0), new Size(this.Width, this.Height));

            if (i.GetPixel(x, y).R == i.GetPixel(x, y).G && i.GetPixel(x, y).B == i.GetPixel(x, y).G)
            {
                result = false;
            }
            else if (int.Parse(i.GetPixel(x, y).R.ToString()) + int.Parse(i.GetPixel(x, y).G.ToString()) + int.Parse(i.GetPixel(x, y).G.ToString()) < 300)
            {
                result = false;
            }
            else
            {
                result = true;
            }

            if (tableno == 1) lbStatus1.Text = i.GetPixel(x, y).R.ToString() + "," + i.GetPixel(x, y).G.ToString() + "," + i.GetPixel(x, y).B.ToString();
            if (tableno == 2) lbStatus2.Text = i.GetPixel(x, y).R.ToString() + "," + i.GetPixel(x, y).G.ToString() + "," + i.GetPixel(x, y).B.ToString();
            if (tableno == 3) lbStatus3.Text = i.GetPixel(x, y).R.ToString() + "," + i.GetPixel(x, y).G.ToString() + "," + i.GetPixel(x, y).B.ToString();


            g.Dispose();
            i.Dispose();

            return result;
        }

        private void Calc()
        {
            this.lbTableSizeTotal.Text = (from bl in BetList where bl.BetStatus == 6 && bl.BetResult != "D" select bl.BetSize).Sum().ToString();
            this.lbTableWinTotal.Text = (from bl in BetList where bl.BetStatus == 6 select bl.BetProfit).Sum().ToString();
            this.lbTotalSum1.Text = (from bl in BetList where bl.BetStatus == 6 && bl.BetProfit > 0 select bl).Count().ToString() + "W "
                + (from bl in BetList where bl.BetStatus == 6 && bl.BetProfit == 0 select bl).Count().ToString() + "D "
                + (from bl in BetList where bl.BetStatus == 6 && bl.BetProfit < 0 select bl).Count().ToString() + "L";


            this.lbRoundID1.Text = RoundID1;
            this.lbTableSize1.Text = (from bl in BetList where bl.BetStatus == 6 && bl.BetResult != "D" && bl.TableNo == 1 select bl.BetSize).Sum().ToString();
            this.lbTableWin1.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 1 select bl.BetProfit).Sum().ToString();
            this.lbTableSum1.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 1 && bl.BetProfit > 0 select bl).Count().ToString() + "W "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 1 && bl.BetProfit == 0 select bl).Count().ToString() + "D "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 1 && bl.BetProfit < 0 select bl).Count().ToString() + "L";
            this.lbTableRoundSum1.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 1 && bl.BetProfit > 0 && bl.RoundID == RoundID1 select bl).Count().ToString() + "W "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 1 && bl.BetProfit == 0 && bl.RoundID == RoundID1 select bl).Count().ToString() + "D "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 1 && bl.BetProfit < 0 && bl.RoundID == RoundID1 select bl).Count().ToString() + "L";


            this.lbRoundID2.Text = RoundID2;
            this.lbTableSize2.Text = (from bl in BetList where bl.BetStatus == 6 && bl.BetResult != "D" && bl.TableNo == 2 select bl.BetSize).Sum().ToString();
            this.lbTableWin2.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 2 select bl.BetProfit).Sum().ToString();
            this.lbTableSum2.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 2 && bl.BetProfit > 0 select bl).Count().ToString() + "W "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 2 && bl.BetProfit == 0 select bl).Count().ToString() + "D "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 2 && bl.BetProfit < 0 select bl).Count().ToString() + "L";
            this.lbTableRoundSum2.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 2 && bl.BetProfit > 0 && bl.RoundID == RoundID2 select bl).Count().ToString() + "W "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 2 && bl.BetProfit == 0 && bl.RoundID == RoundID2 select bl).Count().ToString() + "D "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 2 && bl.BetProfit < 0 && bl.RoundID == RoundID2 select bl).Count().ToString() + "L";

            this.lbRoundID3.Text = RoundID3;
            this.lbTableSize3.Text = (from bl in BetList where bl.BetStatus == 6 && bl.BetResult != "D" && bl.TableNo == 3 select bl.BetSize).Sum().ToString();
            this.lbTableWin3.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 3 select bl.BetProfit).Sum().ToString();
            this.lbTableSum3.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 3 && bl.BetProfit > 0 select bl).Count().ToString() + "W "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 3 && bl.BetProfit == 0 select bl).Count().ToString() + "D "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 3 && bl.BetProfit < 0 select bl).Count().ToString() + "L";

            this.lbTableRoundSum3.Text = (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 3 && bl.BetProfit > 0 && bl.RoundID == RoundID3 select bl).Count().ToString() + "W "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 3 && bl.BetProfit == 0 && bl.RoundID == RoundID3 select bl).Count().ToString() + "D "
                + (from bl in BetList where bl.BetStatus == 6 && bl.TableNo == 3 && bl.BetProfit < 0 && bl.RoundID == RoundID3 select bl).Count().ToString() + "L";
        }

        #region Get Game Result
        public Byte GetLastGameResult1()
        {
            Byte result = 0;

            try
            {
                int locationX = 16 + int.Parse(this.txbOffset.Text);
                int hostLocationY = 525;
                int guestLocationY = 562;
                int equalLocationY = 602;

                if (hostPic1 == null || guestPic1 == null || equalPic1 == null)
                {
                    hostPic1 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g1 = Graphics.FromImage(hostPic1);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    guestPic1 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(guestPic1);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    equalPic1 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(equalPic1);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();
                }
                else
                {
                    Bitmap current_hostPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                    Graphics g1 = Graphics.FromImage(current_hostPic);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_guestPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(current_guestPic);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_equalPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(current_equalPic);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();

                    float host = ImageComparison(current_hostPic, hostPic1);
                    float guest = ImageComparison(current_guestPic, guestPic1);
                    float equal = ImageComparison(current_equalPic, equalPic1);

                    if (host < 1)
                    {
                        hostPic1 = current_hostPic;
                        result = 9;
                    }
                    else if (guest < 1)
                    {
                        guestPic1 = current_guestPic;
                        result = 1;
                    }
                    else if (equal < 1)
                    {
                        equalPic1 = current_equalPic;
                        result = 5;
                    }
                    else
                    {
                        result = 0;
                    }

                    if (host < 1 && guest < 1 && equal < 1)
                    {
                        result = 10;
                        hostPic1 = current_hostPic;
                        guestPic1 = current_guestPic;
                        equalPic1 = current_equalPic;
                        SaveRoad(RoundID1);
                        RoundID1 = "1-" + DateTime.Now.ToString("MMddHHmm");
                    }
                }
            }
            catch (Exception ex)
            {
                result = 0;
                Console.WriteLine(ex.Message.ToString());
            }

            return result;

        }

        public Byte GetLastGameResult2()
        {
            Byte result = 0;

            try
            {
                int locationX = 302 + int.Parse(this.txbOffset.Text);
                int hostLocationY = 525;
                int guestLocationY = 562;
                int equalLocationY = 602;

                if (hostPic2 == null || guestPic2 == null || equalPic2 == null)
                {
                    hostPic2 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g1 = Graphics.FromImage(hostPic2);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    guestPic2 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(guestPic2);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    equalPic2 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(equalPic2);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();
                }
                else
                {
                    Bitmap current_hostPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g1 = Graphics.FromImage(current_hostPic);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_guestPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(current_guestPic);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_equalPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(current_equalPic);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();

                    float host = ImageComparison(current_hostPic, hostPic2);
                    float guest = ImageComparison(current_guestPic, guestPic2);
                    float equal = ImageComparison(current_equalPic, equalPic2);

                    if (host < 1)
                    {
                        hostPic2 = current_hostPic;
                        result = 9;
                    }
                    else if (guest < 1)
                    {
                        guestPic2 = current_guestPic;
                        result = 1;
                    }
                    else if (equal < 1)
                    {
                        equalPic2 = current_equalPic;
                        result = 5;
                    }
                    else
                    {
                        result = 0;
                    }

                    if (host < 1 && guest < 1 && equal < 1)
                    {
                        result = 10;
                        hostPic2 = current_hostPic;
                        guestPic2 = current_guestPic;
                        equalPic2 = current_equalPic;
                        SaveRoad(RoundID2);
                        RoundID2 = "2-" + DateTime.Now.ToString("MMddHHmm");
                    }
                }
            }
            catch (Exception ex)
            {
                result = 0;
                Console.WriteLine(ex.Message.ToString());
            }

            return result;

        }

        public Byte GetLastGameResult3()
        {
            Byte result = 0;

            try
            {
                int locationX = 587 + int.Parse(this.txbOffset.Text);
                int hostLocationY = 525;
                int guestLocationY = 562;
                int equalLocationY = 602;

                if (hostPic3 == null || guestPic3 == null || equalPic3 == null)
                {
                    hostPic3 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g1 = Graphics.FromImage(hostPic3);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    guestPic3 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(guestPic3);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    equalPic3 = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(equalPic3);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();
                }
                else
                {
                    Bitmap current_hostPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                    Graphics g1 = Graphics.FromImage(current_hostPic);
                    g1.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + hostLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_guestPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g2 = Graphics.FromImage(current_guestPic);
                    g2.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + guestLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    Bitmap current_equalPic = new Bitmap(blockWidth, blockHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g3 = Graphics.FromImage(current_equalPic);
                    g3.CopyFromScreen(new Point(this.Location.X + locationX, this.Location.Y + equalLocationY), new Point(0, 0), new Size(blockWidth, blockHeight));

                    g1.Dispose();
                    g2.Dispose();
                    g3.Dispose();

                    float host = ImageComparison(current_hostPic, hostPic3);
                    float guest = ImageComparison(current_guestPic, guestPic3);
                    float equal = ImageComparison(current_equalPic, equalPic3);

                    if (host < 1)
                    {
                        hostPic3 = current_hostPic;
                        result = 9;
                    }
                    else if (guest < 1)
                    {
                        guestPic3 = current_guestPic;
                        result = 1;
                    }
                    else if (equal < 1)
                    {
                        equalPic3 = current_equalPic;
                        result = 5;
                    }
                    else
                    {
                        result = 0;
                    }

                    if (host < 1 && guest < 1 && equal < 1)
                    {
                        result = 10;
                        hostPic3 = current_hostPic;
                        guestPic3 = current_guestPic;
                        equalPic3 = current_equalPic;
                        SaveRoad(RoundID3);
                        RoundID3 = "3-" + DateTime.Now.ToString("MMddHHmm");
                    }
                }
            }
            catch (Exception ex)
            {
                result = 0;
                Console.WriteLine(ex.Message.ToString());
            }

            return result;

        }

        public Byte IsOnline()
        {
            Byte result;
            int x = 568;
            int y = 330;

            Bitmap i;
            Graphics g;

            i = new Bitmap(this.Width, this.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            g = Graphics.FromImage(i);
            g.CopyFromScreen(new Point(this.Location.X, this.Location.Y), new Point(0, 0), new Size(this.Width, this.Height));

            if (int.Parse(i.GetPixel(x, y).R.ToString()) + int.Parse(i.GetPixel(x, y).G.ToString()) + int.Parse(i.GetPixel(x, y).G.ToString()) < 100)
            {
                result = 0;
            }
            else
            {
                result = 1;
            }

            g.Dispose();
            i.Dispose();

            return result;

        }
        #endregion

        #region ClickBet & Submit
        private void ClickBet(Byte tableno, string direction, Decimal betsize)
        {
            string bsize = betsize.ToString("F0");
            if (bsize.Length > 3)
            {
                int tcount = int.Parse(bsize[bsize.Length - 4].ToString());
                ClickChip(tcount, 4, direction, tableno);
            }

            if (bsize.Length > 2)
            {
                int tcount = int.Parse(bsize[bsize.Length - 3].ToString());
                ClickChip(tcount, 3, direction, tableno);
            }

            if (bsize.Length > 1)
            {
                int tcount = int.Parse(bsize[bsize.Length - 2].ToString());
                ClickChip(tcount, 2, direction, tableno);
            }

            if (ConfigurationManager.AppSettings["IsSubmit"] == "1") ClickSubmit(tableno);
        }

        private void ClickChip(int count, int psize, string direction, Byte tableno)
        {
            if (count == 0) return;

            //计算筹码坐标
            int ybase = 495;
            int xbase = 80 + int.Parse(this.txbOffset.Text) + (tableno - 1) * 285 + (psize - 2) * 44;
            //计算庄闲位置坐标
            int ydbase = 400;
            int xdbase = ((direction == "B") ? 230 : 88) + (tableno - 1) * 285;

            //点击筹码
            SetCursorPos(xbase + this.Location.X, ybase + this.Location.Y);
            mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
            mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);

            Thread.Sleep(500);

            //点击庄闲位置
            for (int i = 0; i < count; i++)
            {
                SetCursorPos(xdbase + this.Location.X, ydbase + this.Location.Y);
                mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
                mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);
            }

            
        }

        private void ClickSubmit(Byte tableno)
        {
            int ybase = 450;
            int xbase = 216 + (tableno - 1) * 285;

            SetCursorPos(xbase + this.Location.X, ybase + this.Location.Y);
            mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, 0);
            mouse_event(MouseEventFlag.LeftUp, 0, 0, 0, 0);

            LastSubmitTime = DateTime.Now;
        }
        #endregion

        #region Base Func for Click & Window
        public float ImageComparison(Bitmap img1, Bitmap img2)
        {
            if (img1.Width == img2.Width && img1.Height == img2.Height && img1.Width != 0 && img1.Height != 0)
            {
                int equalCount = 0;

                for (int i = 0; i < img1.Width; i++)
                {
                    for (int j = 0; j < img1.Height; j++)
                    {
                        if (img1.GetPixel(i, j) == img2.GetPixel(i, j))
                        {
                            equalCount++;
                        }
                    }
                }

                return (float)equalCount / (img1.Width * img1.Height);
            }
            else
            {
                return 0;
            }
        }

        public void wbMain_NewWindow(string url, int flag, string target, ref object data, string header, ref bool processed)
        {
            processed = true;
            wbMain.Navigate(url);
        }

        /// <summary>
        /// 这部分是控制鼠标定位的基础类和方法，不用管，已经封装好了。
        /// </summary>
        #region Mouse Base Action
        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);
        [Flags]
        enum MouseEventFlag : uint
        {
            Move = 0x0001,
            LeftDown = 0x0002,
            LeftUp = 0x0004,
            RightDown = 0x0008,
            RightUp = 0x0010,
            MiddleDown = 0x0020,
            MiddleUp = 0x0040,
            XDown = 0x0080,
            XUp = 0x0100,
            Wheel = 0x0800,
            VirtualDesk = 0x4000,
            Absolute = 0x8000
        }

        [DllImport("user32.dll")]
        static extern void mouse_event(MouseEventFlag flags, int dx, int dy, int cButtons, int dwExtraInfo);
        #endregion

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {

            if (keyData.ToString() == "F2")
            {
                if (btnStartGame.Text == "开始")
                {
                    HtmlElementCollection eles = wbMain.Document.Window.Frames[0].Document.GetElementsByTagName("object");

                    foreach (HtmlElement ele in eles)
                    {
                        if (ele.InnerHtml.Contains("MultiBetEmbed.swf")) ele.Style = "position: absolute; z-index: 9999; top: 0px; left: 0px; width:860px; height: 600px; visibility: visible;";
                    }


                    btnStartGame.Text = "暂停";
                    OnStart();


                    timerMain.Enabled = true;
                    timerMain.Start();
                }
                else
                {
                    timerMain.Stop();
                    btnStartGame.Text = "开始";
                    this.TopMost = false;
                }
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        protected string ConvertResult(Byte r)
        {
            string rs = "";

            switch (r)
            {
                case 9:
                    rs = "B";
                    break;
                case 1:
                    rs = "P";
                    break;
                case 5:
                    rs = "D";
                    break;
                default:
                    rs = "";
                    break;
            }

            return rs;
        }
        #endregion

        public void SaveRoad(string roundid)
        {
            List<Bet> roadList = (from rl in BetList where rl.RoundID == roundid orderby rl.BetTime ascending select rl).ToList();

            if (roadList.Count > 50)
            {

                if (File.Exists(roundid + ".txt")) File.Delete(roundid + ".txt");
                FileStream fileStream = File.OpenWrite(roundid + ".txt");
                StreamWriter sw = new StreamWriter(fileStream);

                foreach (Bet b in roadList)
                {
                    string p = "D";
                    if (b.BetProfit > 0) p = "W";
                    if (b.BetProfit < 0) p = "L";
                    sw.WriteLine(b.BetTime.ToString("YYYY-MM-dd HH:mm:ss") + "|" + b.Direction + "|" + b.BetResult + "|" + p);
                }

                sw.WriteLine("--------------------------------------------");
                sw.WriteLine((from rl in roadList where rl.BetProfit > 0 select rl).Count().ToString() + "W," + (from rl in roadList where rl.BetProfit == 0 select rl).Count().ToString() + "D," + (from rl in roadList where rl.BetProfit < 0 select rl).Count().ToString() + "L");

                sw.Close();
                fileStream.Close();
            }
        }
    }
}
